<template>
  <div class="multipass_query animate__animated animate__fadeIn">
    <div class="multipass">
      <el-form ref="formRef" :model="dynamicValidateForm" class="demo-dynamic">
        <el-row class="div_row">
          <el-col :span="7">
            <div class="upCity">
              <el-form-item prop="upCity" @click="upCard = !upCard" :rules="[{
                required: true,
                message: '出发城市不能为空',
                trigger: 'blur',
              }]">
                <el-input v-model="dynamicValidateForm.upCity" placeholder="出发城市" size="large" maxlength="10"
                  :prefix-icon="LocalTwo" @blur="upCard = false" />
                <div class="card" v-show="upCard">
                  <el-card class="box-card">
                    <template #header>
                      <div class="card-header">
                        <span>出发城市</span>
                      </div>
                    </template>
                    <div v-for="item in city" class="text" :key="item.index">
                      <div @mousedown="upCityChoice(item)">
                        {{ item }}
                      </div>
                    </div>
                  </el-card>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="1">
            <el-button @click="exchange" class="switch_btn">
              <Switch theme="outline" size="24" fill="#333" />
            </el-button>
          </el-col>
          <el-col :span="7">
            <div class="downCity">
              <el-form-item prop="downCity" @click="downCard = !downCard" :rules="[
                {
                  required: true,
                  message: '目的地城市不能为空',
                  trigger: 'blur',
                }
              ]">
                <el-input v-model="dynamicValidateForm.downCity" placeholder="到达城市" size="large" maxlength="10"
                  @blur="downCard = false" :prefix-icon="LocalTwo" />
                <div class="card" v-show="downCard">
                  <el-card class="box-card">
                    <template #header>
                      <div class="card-header">
                        <span>到达城市</span>
                      </div>
                    </template>
                    <div v-for="item in city" class="text" :key="item.index">
                      <div @mousedown="downCityChoice(item)">
                        {{ item }}
                      </div>
                    </div>
                  </el-card>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="7" style="margin-left: 30px;">
            <div class="upDate">
              <el-form-item prop="upDate" :rules="[
                {
                  required: true,
                  message: '出发日期不能为空',
                  trigger: 'blur'
                },
                {
                  validator: validateRoundendTime,
                  trigger: 'blur'
                },
              ]">
                <el-date-picker v-model="dynamicValidateForm.upDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                  type="date" placeholder="出发日期" size="large" :disabled-date="disabled" style="width: 300px" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <!--  -->
        <el-row class="div_row" v-for="(data, index) in dynamicValidateForm.domains" :key="index">
          <el-col :span="7">
            <div class="upCity">
              <el-form-item :prop="'domains.' + index + '.upCity'" @click="data.upCard_state = !data.upCard_state"
                :rules="[
                  {
                    required: true,
                    message: '出发城市不能为空',
                    trigger: 'blur',
                  }
                ]">
                <el-input v-model="data.upCity" placeholder="出发城市" size="large" maxlength="10" :prefix-icon="LocalTwo"
                  @blur="data.upCard_state = false" />
                <div class="card" v-show="data.upCard_state">
                  <el-card class="box-card">
                    <template #header>
                      <div class="card-header">
                        <span>出发城市</span>
                      </div>
                    </template>
                    <div v-for="item in city" class="text" :key="item.index">
                      <div @mousedown="upCityChoiceList(item, data.id)">
                        {{ item }}
                      </div>
                    </div>
                  </el-card>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="1">
            <el-button @click="permutation(data)" class="switch_btn">
              <Switch theme="outline" size="24" fill="#333" />
            </el-button>
          </el-col>
          <el-col :span="7">
            <div class="downCity">
              <el-form-item :prop="'domains.' + index + '.downCity'" @click="data.downCard_state = !data.downCard_state"
                :rules="[
                  {
                    required: true,
                    message: '目的地城市不能为空',
                    trigger: 'blur',
                  }
                ]">
                <el-input v-model="data.downCity" placeholder="到达城市" size="large" maxlength="10"
                  @blur="data.downCard_state = false" :prefix-icon="LocalTwo" />
                <div class="card" v-show="data.downCard_state">
                  <el-card class="box-card">
                    <template #header>
                      <div class="card-header">
                        <span>到达城市</span>
                      </div>
                    </template>
                    <div v-for="item in city" class="text" :key="item.index">
                      <div @mousedown="downCityChoiceList(item, data.id)">
                        {{ item }}
                      </div>
                    </div>
                  </el-card>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="7" style="margin-left: 30px;">
            <div class="upDate">
              <el-form-item :prop="'domains.' + index + '.upDate'" :rules="[
                {
                  required: true,
                  message: '出发日期不能为空',
                  trigger: 'blur',
                },
                {
                  validator: validateendTime,
                  trigger: 'blur'
                }
              ]">
                <el-date-picker v-model="data.upDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="date"
                  placeholder="出发日期" size="large" :disabled-date="multipassDisabled[index]" style="width: 300px" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="1" v-show="data.id != 2">
            <el-button class="close_one" @click="removeDomain(data)">
              <close-one theme="outline" size="24" fill="#333" />
            </el-button>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="addDomain">+ 再加一程</el-button>
          <el-button @click="submitForm(formRef)" type="warning" color="rgb(10,22,46)" class="search_btn" size="large"
            round :icon="Search">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, watch } from 'vue'
import { Switch, LocalTwo, CloseOne, Search } from "@icon-park/vue-next"
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import url from "../../common/js/APIUtil";

// 城市选择
var city = ref([])
var upCard = ref(false);
var downCard = ref(false);
let upCard_state = false
let downCard_state = false
//路由
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
// 表单验证
const formRef = ref()
const dynamicValidateForm = reactive({
  id: 1,
  upCity: '',
  downCity: '',
  upDate: '',
  domains: [{ id: 2, upCity: '', downCity: '', upDate: '', upCard_state: false, downCard_state: false },]
})
//数据存放
const multipass = reactive({
  upCity: [],
  downCity: [],
  upDate: []
})

// 将输入框的数据添加到列表
const multipass_add = () => {
  multipass.upCity.push(dynamicValidateForm.upCity)
  multipass.downCity.push(dynamicValidateForm.downCity)
  multipass.upDate.push(dynamicValidateForm.upDate)
  if (dynamicValidateForm.domains) {
    for (var i = 0; i < dynamicValidateForm.domains.length; i++) {
      multipass.upCity.push(dynamicValidateForm.domains[i].upCity)
      multipass.downCity.push(dynamicValidateForm.domains[i].downCity)
      multipass.upDate.push(dynamicValidateForm.domains[i].upDate)
    }
  }
}
//搜索后删除数据
const multipass_clear = () => {
  multipass.upCity = []
  multipass.downCity = []
  multipass.upDate = []
}

const disabled = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
}
//多程时间限制
var multipassDisabled = reactive(['', '', '', ''])

//输入框数据交换
const exchange_data = ref();
const exchange = () => {
  exchange_data.value = dynamicValidateForm.upCity;
  dynamicValidateForm.upCity = dynamicValidateForm.downCity;
  dynamicValidateForm.downCity = exchange_data.value;
};
const permutation_data = ref()
const permutation = (item) => {
  for (var i = 0; i < dynamicValidateForm.domains.length; i++) {
    if (item.id == dynamicValidateForm.domains[i].id) {
      permutation_data.value = dynamicValidateForm.domains[i].upCity
      dynamicValidateForm.domains[i].upCity = dynamicValidateForm.domains[i].downCity
      dynamicValidateForm.domains[i].downCity = permutation_data.value
    }
  }
}

// 删除一程
const removeDomain = (item) => {
  const index = dynamicValidateForm.domains.indexOf(item)
  if (index !== 0) {
    dynamicValidateForm.domains.splice(index, 1)
  }
}
// 再加一程
let key = ref(2)
const addDomain = () => {
  key.value += 1
  if (dynamicValidateForm.domains.length != 4) {
    dynamicValidateForm.domains.push({
      id: key.value,
      upCity: '',
      downCity: '',
      upDate: '',
      upCard_state: false,
      downCard_state: false
    })
  } else {
    ElMessage.error("不能再加啦")
  }
}

//监视搜索数据而改变日期限制
watch(() => dynamicValidateForm.domains, () => {
  multipassDisabled[0] = (time) => {
    if (dynamicValidateForm.upDate != '' && dynamicValidateForm.upDate != null) {
      return time.getTime() < new Date(Date.parse(dynamicValidateForm.upDate.replace(/-/g, "/")) + 8.64e7);
    } else {
      return time.getTime() < Date.now() - 8.64e7;
    }
  };
  for (let i = 1; i < dynamicValidateForm.domains.length; i++) {
    multipassDisabled[i] = (time) => {
      let date = ''
      for (let j = i; j > 0; j--) {
        if (dynamicValidateForm.domains[j - 1].upDate != '' && dynamicValidateForm.domains[j - 1].upDate != null) {
          date = dynamicValidateForm.domains[j - 1].upDate
          break;
        }
      }
      if (date == '' && dynamicValidateForm.upDate != '' && dynamicValidateForm.upDate != null) {
        date = dynamicValidateForm.upDate
      } else if (date == '') {
        return time.getTime() < Date.now() - 8.64e7;
      }
      return time.getTime() < new Date(Date.parse(date.replace(/-/g, "/")) + 8.64e7);
    }
  }
}, { immediate: true, deep: true })

//多层日期验证(第一个日期搜索框)
let validateRoundendTime = (rule, value, callback,) => {
  let have = false
  for (let index = 0; index < dynamicValidateForm.domains.length; index++) {
    if (new Date(dynamicValidateForm.domains[index].upDate).getTime() <= new Date(value).getTime()) {
      have = true
    }
  }

  if (have) {
    callback(new Error('先程日期不能晚于或等于后程日期'))
  } else {
    callback()
  }

}

//多程日期验证(后面日期搜索框)
let validateendTime = (rule, value, callback,) => {
  let have = false
  let num = -1
  for (let index = 0; index < dynamicValidateForm.domains.length; index++) {
    if (dynamicValidateForm.domains[index].upDate == value) {
      num = index + 1
      break
    }
  }
  for (let index = num; index < dynamicValidateForm.domains.length; index++) {
    if (new Date(dynamicValidateForm.domains[index].upDate).getTime() <= new Date(value).getTime()) {
      have = true
    }
  }
  if (new Date(dynamicValidateForm.upDate).getTime() == new Date(value).getTime()) {
    have = true
  }

  if (have) {
    callback(new Error('先程日期不能晚于或等于后程日期'))
  } else {
    callback()
  }
}

// 搜索
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      multipass_add()
      let writeData = {
        upCity: multipass.upCity.join("_"),
        downCity: multipass.downCity.join("_"),
        upDate: multipass.upDate.join("_")
      }
      router.push({
        path: '/index/ticketinformation/multipass',
        query: {
          upCity: writeData.upCity,
          downCity: writeData.downCity,
          upDate: writeData.upDate,
        },
      });
      multipass_clear()
    } else {
      ElMessage.warning("请调整数据再请搜索")
      return false
    }
  })
}
// 获取城市数据
const getCityAll = () => {
  proxy.$http.get(url.API_GET_citAll).then((res) => {
    city.value = Array.from(new Set(res.data.map(value => value.name)))
  });
};
getCityAll();

const upCityChoice = (value) => {
  dynamicValidateForm.upCity = value;
  upCard.value = false;
};
const downCityChoice = (value) => {
  dynamicValidateForm.downCity = value;
  downCard.value = false;
};

const upCityChoiceList = (value, data_id) => {
  for (var i = 0; i < dynamicValidateForm.domains.length; i++) {
    if (data_id == dynamicValidateForm.domains[i].id) {
      dynamicValidateForm.domains[i].upCity = value;
    }
  }
  upCard.value = false;
};
const downCityChoiceList = (value, data_id) => {
  for (var i = 0; i < dynamicValidateForm.domains.length; i++) {
    if (data_id == dynamicValidateForm.domains[i].id) {
      dynamicValidateForm.domains[i].downCity = value;
    }
  }
  downCard.value = false;
};
</script>

<style lang="less" scoped>
.multipass_query {
  width: 100%;
  background-color: rgb(255, 255, 255);
  border-radius: 0px 15px 15px 0px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.multipass {
  width: 1100px;
  margin: auto;
  padding: 0px 0px 0px 15px;
  margin-top: 15px;
}

/* 出发地 */
.upCity {
  width: 330px;
}

/* 目的地 */
.downCity {
  width: 330px;
  margin-left: 5px;
}

/* 出发日期 */
.upDate {
  width: 300px;
  margin-left: 10px;
}

.div_row {
  margin-left: 10px;
  height: 69px;
}

.close_one {
  border: none;
  margin: auto;
  transform: translate(0%, 60%);
  background-color: rgba(0, 0, 0, 0.0);
}

.switch_btn {
  width: 40px;
  height: 35px;
  border: none;
  margin: auto;
  transform: translate(4%, 55%);
  background-color: rgba(0, 0, 0, 0.0);
}

.search_btn {
  font-size: 18px;
  height: 40px;
  width: 134px;
  margin-left: 370px;
}

.card-header {
  height: 5px;
  transform: translate(0%, -140%);
}

.card {
  position: absolute;
  pointer-events: auto;
  width: 400px;
  top: 67px;
  z-index: 2000;
}

.text {
  float: left;
  font-size: 15px;
  margin-right: 20px;
  margin-bottom: 20px;
  cursor: pointer;
}

.text:hover {
  color: rgba(6, 127, 249);
  background-color: rgba(6, 127, 249, 0.1);
}

:deep(.el-input--large .el-input__inner) {
  height: 50px;
}

:deep(.el-input__wrapper) {
  border-radius: 10px;
}

:deep(.el-input--large) {
  font-size: 18px;
}

:deep(.el-form-item--small) {
  --font-size: 12px;
  --el-form-label-font-size: var(--font-size);
  margin-bottom: 10px;
}

.el-button.is-round {
  border-radius: 8px;
}

.el-button--small {
  --el-button-size: 24px;
  height: var(--el-button-size);
  padding: 5px 11px;
  font-size: 12px;
  border-radius: calc(var(--el-border-radius-base) - 1px);
  margin-left: 10px;
}
</style>